#!/usr/local/bin/php
<?php
require_once 'common.php';

/* @var $logger Log */
global $logger;
global $dbOaIIOaWeb;
global $dbOaIIOa;
global $dbOaIIOaPre;
global $dbOaIIOas;
global $dbOaIIOasPre;
/* @var $userMigrationTable OpTableModel */
global $userMigrationTable;
/* @var $developerTable OpTableModel */
global $developerTable;
/* @var $companyTable OpTableModel */
global $companyTable;
/* @var $companyDeveloperTable OpTableModel */
global $companyDeveloperTable;
/* @var $appTable OpTableModel */
global $appTable;
/* @var $appConfigTable OpTableModel */
global $appConfigTable;
/* @var $appDeveloperTable OpTableModel */
global $appDeveloperTable;
/* @var $appAreaTable OpTableModel */
global $appAreaTable;
/* @var $appGroupTable OpTableModel */
global $appGroupTable;
/* @var $appServerTable OpTableModel */
global $appServerTable;
/* @var $appLoginServerTable OpTableModel */
global $appLoginServerTable;
/* @var $appLoginServerValidTable OpTableModel */
global $appLoginServerValidTable;
/* @var $appPayServerTable OpTableModel */
global $appPayServerTable;
/* @var $appPayServerValidTable OpTableModel */
global $appPayServerValidTable;
/* @var $appConfigOrderTable OpTableModel */
global $appConfigOrderTable;
/* @var $appSnapshotTable OpTableModel */
global $appSnapshotTable;

$options = getopt('a:f:g:s');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " [-a import|delete] [-f app_list_file|-g app_id] [-s]");
    exit();
}
if (isset($options['a'])) {
    $action = $options['a'];
} else {
    $action = 'import';
}
if (!in_array($action, array('import', 'delete'))) {
    $logger->err("wrong action");
    exit();
}
if (isset($options['f'])) {
    $contents = file_get_contents($options['f']);
    if ($contents === false) {
        $logger->err("get file contents failed");
        exit();
    }
} else if (isset($options['g'])) {
    $contents = $options['g'];
} else {
    $logger->err("no app specified");
    exit();
}
if (isset($options['s'])) {
    $force = true;
} else {
    $force = false;
}

$rows = explode("\n", trim($contents));
if ($action == 'import') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $appId = isset($row[0]) ? intval($row[0]) : 0;
        if ($appId < 0) {
            $logger->warning("app id invalid: app_id-$appId");
            continue;
        }
        
        // 从TB_SERVICE表读取游戏信息
        $sql = "SELECT SERVICEID, SVRNAME, SPID, TIMETYPEID, CREATEUSER, 
        	TO_CHAR(CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME, 
        	TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME, 
        	NOTES, SIGNARITH, MANAGEID FROM TB_SERVICE WHERE SERVICEID=:app_id";
        $st = oci_parse($dbOaIIOa, $sql);
        oci_bind_by_name($st, ':app_id', $appId);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
            exit();
        }
        $app = oci_fetch_assoc($st);
        if ($app === false) {
            $logger->warning("app not exists: app_id-$appId");
            continue;
        }
        $companyId = $app['SPID'];
        if ($companyId <= 0) {
            $logger->warning("invalid company: company-$companyId");
            continue;
        }
        
        $testAppId = getTestAppId($appId, $message);
        if ($testAppId == false) {
            $logger->warning("get test app id failed: app_id-$appId, message-$message");
            continue;
        }
        
        // 从TBTYPE表读取游戏币名称
        $sql = "SELECT TYPENAME FROM TBTYPE WHERE TYPECODE=:app_id";
        $st = oci_parse($dbOaIIOa, $sql);
        oci_bind_by_name($st, ':app_id', $appId);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
            exit();
        }
        $row = oci_fetch_assoc($st);
        if ($row) {
            $gameCurrencyName = $row['TYPENAME'];
        } else {
            $gameCurrencyName = '';
        }
        // 从TBRATE表读取游戏币兑换比率
        $sql = "SELECT DENOMINATOR FROM TBRATE WHERE SERVICEID=:app_id";
        $st = oci_parse($dbOaIIOa, $sql);
        oci_bind_by_name($st, ':app_id', $appId);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
            exit();
        }
        $row = oci_fetch_assoc($st);
        if ($row) {
            $gameCurrencyRate = $row['DENOMINATOR'];
        } else {
            $gameCurrencyRate = '';
        }
        // 查询游戏创建者数字帐号
        $appCreator = getUidByUserId($app['CREATEUSER'], $message);
        if ($appCreator === false) {
            $logger->warning($message);
            continue;
        }
        // 转换游戏类型
        if (in_array($appId, array(4, 60, 2, 48, 70, 14, 64, 10064, 11181, 
            12345, 312099, 10047, 8502))) {
            $app['MANAGEID'] = OaAppModel::APP_TYPE_CLIENT;
        } else if (in_array($appId, array(643, 640, 617, 629, 605, 632, 628, 
            624, 620, 623, 619, 616, 608, 102, 600, 601, 597, 590, 595))) {
            $app['MANAGEID'] = OaAppModel::APP_TYPE_WEB_PAGE;
        } else if (in_array($appId, array(801, 604, 95, 303, 206))) {
            $app['MANAGEID'] = OaAppModel::APP_TYPE_WEB_SITE;
        }
        
        // 迁移公司信息（先检查是否已迁移过）
        if (is_null($companyTable->getRow(array(
            'id' => $companyId
        )))) {
            if (!importCompany($companyId, $message)) {
                $logger->warning($message);
                continue;
            } else {
                $logger->info("import company succeed, company-$companyId");
            }
        } else {
            $logger->info("company already imported, company-$companyId");
        }
        
        // 插入应用表
        if (!$appTable->insert(array(
            'id' => $appId,
            'name' => $app['SVRNAME'],
            'status' => OaAppModel::APP_STATUS_IN_OPERATION,
            'company_id' => $companyId,
            'pay_type' => $app['TIMETYPEID'],
            'creator' => $appCreator,
            'create_time' => $app['CREATETIME'],
            'tm' => $app['UPDATETIME'],
            'notes' => $app['NOTES'],
            'encrypt_type' => $app['SIGNARITH'],
            'type' => $app['MANAGEID'],
            'game_currency_name' => $gameCurrencyName,
            'game_currency_rate' => $gameCurrencyRate,
            'join_type' => 2
        ))) {
            $logger->warning("insert app failed: app_id-$appId");
            continue;
        } else {
            $logger->info("insert app ok: app_id-$appId");
        }
        
        // 插入应用配置表
        if (!$appConfigTable->insert(array(
            'environment' => OaAppModel::APP_CONFIG_ENV_TEST,
            'app_id' => $appId
        ), null, false)) {
            $logger->warning("insert app test config failed: app_id-$appId");
            continue;
        } else {
            $logger->info("insert app test config ok: app_id-$appId");
        }
        if (!$appConfigTable->insert(array(
            'environment' => OaAppModel::APP_CONFIG_ENV_PRODUCTION,
            'app_id' => $appId
        ), null, false)) {
            $logger->warning("insert app production config failed: app_id-$appId");
            continue;
        } else {
            $logger->info("insert app production config ok: app_id-$appId");
        }
        
        // 同步应用信息到连调环境
        $appModel = new OaAppModel(OaAppModel::APP_CONFIG_ENV_TEST, $logger);
        $codeModel = new OaCodeModel($logger);
        $app = $appModel->getApp($appId);

 //       $logger->info("sync to code succeed: app-$appId");
        $params = array(
            'appId' => $appId,
            'typeId' => 1,
            'appName' => $app['name'],
            'spId' => $app['company_id'],
            'timeTypeId' => $app['pay_type'],
            'createUser' => $app['creator'],
            'manageId' => $app['type'],
            'auditFlag' => $app['status'],
            'note' => '',
            'signarith' => $app['encrypt_type']
        );
        if (!empty($app['game_currency_name'])) {
        	$params['currencyList'] = array(
                array(
                	'currencyName' => $app['game_currency_name'], 
                	'currencyRate' => $app['game_currency_rate']
                )
            );
        }
 //       OAApi::app($message, $params, 'add', OaAppModel::APP_CONFIG_ENV_TEST);
 //       OAApi::app($message, $params, 'update', OaAppModel::APP_CONFIG_ENV_TEST);
 //       $logger->info("sync to oa succeed: app-$appId");
        $params = array(
            'appId' => $appId,
            'typeId' => 1,
            'appName' => $app['name'],
            'status' => $app['status'],
            'spId' => $app['company_id'],
            'timeTypeId' => $app['pay_type'],
            'createUser' => $app['creator'],
            'payTypeId' => 3,
            'manageId' => $app['type'],
            'signArith' => $app['encrypt_type']
        );
   //     OASApi::app($message, $params, 'add', OaAppModel::APP_CONFIG_ENV_TEST);
   //     OASApi::app($message, $params, 'update', OaAppModel::APP_CONFIG_ENV_TEST);
//        $logger->info("sync to oas succeed: app-$appId");
        
        if (!importKey($appId, OaAppModel::APP_CONFIG_ENV_PRODUCTION, $message)) {
            $logger->warning($message);
            continue;
        } else {
            $logger->info("import production key ok: app_id-$appId");
        }
        
        // 抓取二期游戏Logo
        $logoUrl = "http://workshop.open.sdo.com/include/showJPG.jsp?spId=$companyId&serviceId=$appId";
        $logoFilePath = "/uploads/open/app_logos/app_logo_$appId";
        file_put_contents($logoFilePath, file_get_contents($logoUrl));
        $size = getimagesize($logoFilePath);
        if (!is_array($size)) {
            $logger->warning("get image size failed: logo_url-$logoUrl");
            continue;
        }
        if ($size['mime'] == 'image/jpeg') {
            $suffix = 'jpg';
        } else if ($size['mime'] == 'image/gif') {
            $suffix = 'gif';
        } else if ($size['mime'] == 'image/png') {
            $suffix = 'png';
        } else if ($size['mime'] == 'image/bmp') {
            $suffix = 'bmp';
        } else {
            $logger->warning("unknown image type: mime-{$size['mime']}");
            continue;
        }
        rename($logoFilePath, "$logoFilePath.$suffix");
        if (!$appTable->update(array(
            'id' => $appId
        ), array(
            'icon_middle' => "app_logos/app_logo_$appId.$suffix"
        ))) {
            $logger->warning("update logo filed: app_id-$appId");
            continue;
        } else {
            $logger->info("update logo ok: app_id-$appId");
        }
        
        // 导入游戏人员到应用
        $sql = "SELECT US_ID, UG_ID FROM TB_USERGROUP_MEMBER WHERE APPID=:app_id";
        $st = oci_parse($dbOaIIOaWeb, $sql);
        oci_bind_by_name($st, ':app_id', $appId);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
            exit();
        }
        $appAdmin = 0;
        while ($row = oci_fetch_assoc($st)) {
            if ($row['UG_ID'] == 1) {
                $role = OaAuthorityModel::ROLE_APP_ADMIN;
            } else if ($row['UG_ID'] == 3) {
                $role = OaAuthorityModel::ROLE_APP_DEVELOPER;
            } else {
                $role = OaAuthorityModel::ROLE_APP_OPERATOR;
            }
            $appCreator = getUidByUserId($row['US_ID'], $message);
            if ($appCreator === false) {
                $logger->warning("app creator not exists, creator-{$row['US_ID']}");
                continue;
            }
            if (!$appDeveloperTable->getRow(array(
                'app_id' => $appId,
                'developer_id' => $appCreator,
                'role' => $role
            )) && !$appDeveloperTable->insert(array(
                'app_id' => $appId,
                'developer_id' => $appCreator,
                'role' => $role
            ))) {
                $logger->warning("add app member failed: app_id-$appId");
                continue;
            }
            if ($role == OaAuthorityModel::ROLE_APP_ADMIN) {
                $appAdmin = $appCreator;
            }
        }
        $logger->info("import app member ok: app_id-$appId");
        
        // 如果产品管理员在公司中的角色为普通员工，修改其角色为产品经理
        $companyDeveloper = $companyDeveloperTable->getRow(array(
            'company_id' => $companyId,
            'developer_id' => $appAdmin
        ));
        if (is_array($companyDeveloper) && 
            $companyDeveloper['role'] == OaAuthorityModel::ROLE_COMPANY_EMPLOYEE) {
            if (!$companyDeveloperTable->update(array(
                'company_id' => $companyId,
                'developer_id' => $appAdmin
            ), array(
                'role' => OaAuthorityModel::ROLE_COMPANY_PM
            ))) {
                $logger->warning("change app admin role in company failed: company_id-$companyId developer_id-$appAdmin");
                continue;
            }
        }
        
        // 导入游戏区组（连调和正式）
        if (!importAreaGroupServer($appId, OaAppModel::APP_CONFIG_ENV_PRODUCTION, $message)) {
            $logger->warning($message);
            continue;
        } else {
            $logger->info("import production area group server ok: app_id-$appId");
        }
        
        // 导入登录服务器（连调和正式）
        if (!importLoginServer($appId, OaAppModel::APP_CONFIG_ENV_PRODUCTION, $message)) {
            $logger->warning($message);
            continue;
        } else {
            $logger->info("import production login server ok: app_id-$appId");
        }
        
        // 导入充值服务器（连调和正式）
        if (!importPayServer($appId, OaAppModel::APP_CONFIG_ENV_PRODUCTION, $message)) {
            $logger->warning($message);
            continue;
        } else {
            $logger->info("import production pay server ok: app_id-$appId");
        }
        
        // 导入服务配置（连调和正式）
        if (!importServiceConfig($appId, OaAppModel::APP_CONFIG_ENV_PRODUCTION, $message)) {
            $logger->warning($message);
            continue;
        } else {
            $logger->info("import production service config ok: app_id-$appId");
        }
        
        // 生成一个接入订单并给该订单生成一个快照
        $appConfigOrderModel = new OaAppConfigOrderModel($logger);
        $orderId = "order.$appId";
        if (!$appConfigOrderModel->createConfigOrder($orderId, $appId, $appCreator, array(
            'status' => OaAppConfigOrderModel::CONFIG_ORDER_STATUS_IN_OPERATION
        ))) {
            $logger->warning("create order failed: app_id-$appId");
            continue;
        }
                
        $logger->info("import app succeed: app_id=$appId");
    }
} else if ($action == 'delete') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $appId = isset($row[0]) ? intval($row[0]) : 0;
        
        if (!$appTable->delete(array(
            'id' => $appId
        ))) {
            $logger->warning("delete from app table failed");
            continue;
        }
        
        if (!$appConfigTable->delete(array(
            'app_id' => $appId
        ))) {
            $logger->warning("delete from app table failed");
            continue;
        }
        
        if (!$appDeveloperTable->delete(array(
            'app_id' => $appId
        ))) {
            $logger->warning("delete from app developer table failed");
            continue;
        }
        
        $areas = $appAreaTable->get(array(
            'app_id' => $appId
        ));
        foreach ($areas as $area) {
            $groups = $appGroupTable->get(array(
                'area_id' => $area['id']
            ));
            foreach ($groups as $group) {
                if (!$appServerTable->delete(array(
                    'group_id' => $group['id']
                ))) {
                    $logger->warning("delete from app server table failed");
                    continue;
                }
                if (!$appGroupTable->delete(array(
                    'id' => $group['id']
                ))) {
                    $logger->warning("delete from app group table failed");
                    continue;
                }
            }
            if (!$appAreaTable->delete(array(
                'id' => $area['id']
            ))) {
                $logger->warning("delete from app area table failed");
                continue;
            }
        }
        
        $loginServers = $appLoginServerTable->get(array(
            'app_id' => $appId
        ));
        foreach ($loginServers as $loginServer) {
            if (!$appLoginServerValidTable->delete(array(
                'login_server_id' => $loginServer['id']
            ))) {
                $logger->warning("delete from login server valid table failed");
                continue;
            }
            if (!$appLoginServerTable->delete(array(
                'id' => $loginServer['id']
            ))) {
                $logger->warning("delete from login server table failed");
                continue;
            }
        }
        
        $payServers = $appPayServerTable->get(array(
            'app_id' => $appId
        ));
        foreach ($payServers as $payServer) {
            if (!$appPayServerValidTable->delete(array(
                'pay_server_id' => $payServer['id']
            ))) {
                $logger->warning("delete from pay server valid table failed");
                continue;
            }
            if (!$appPayServerTable->delete(array(
                'id' => $payServer['id']
            ))) {
                $logger->warning("delete from pay server table failed");
                continue;
            }
        }
        
        $orderId = "order.$appId";
        if (!$appConfigOrderTable->delete(array(
            'app_id' => $appId
        ))) {
            $logger->warning("delete app order failed");
            continue;
        }
        if (!$appSnapshotTable->delete(array(
            'app_id' => $appId
        ))) {
            $logger->warning("delete app snapshot failed");
            continue;
        }
        
        $logger->info("delete app succeed: app_id=$appId");
    }
}
